<template>
  <el-table
    ref="tableRef"
    :data="tableData"
    border
    v-loading="loading"
    height="100%"
    @selection-change="handleSelectionChange"
    @sort-change="handleSortChange"
    v-bind="$attrs"
  >
    <!-- 选择列 -->
    <el-table-column v-if="showSelection" type="selection" width="55" :reserve-selection="true" />

    <!-- 动态列 - 优化渲染 -->
    <template v-for="column in columns" :key="`col-${column.prop || column.type}`">
      <!-- 展开行类型列 -->
      <el-table-column v-if="column.type === 'expand'" type="expand" :width="column.width || 50">
        <template #default="scope">
          <slot :name="column.slot" :row="scope.row" :index="scope.$index" />
        </template>
      </el-table-column>

      <!-- 普通数据列 -->
      <el-table-column
        v-else
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :min-width="column.minWidth"
        :align="column.align || 'left'"
        :sortable="column.sortable"
        :fixed="column.fixed"
        :show-overflow-tooltip="column['show-overflow-tooltip'] || true"
        :formatter="column.formatter"
      >
        <!-- 性能优化：只在有插槽时才渲染插槽 -->
        <template v-if="column.slot" #default="scope">
          <slot :name="column.slot" :row="scope.row" :index="scope.$index" />
        </template>
      </el-table-column>
    </template>

    <!-- 操作列 -->
    <el-table-column
      v-if="showOperation && !hasOperationColumn"
      :label="operationLabel"
      :width="operationWidth"
      :fixed="operationFixed"
    >
      <template #default="scope">
        <slot name="operation" :row="scope.row" :index="scope.$index">
          <el-button-group v-if="showDefaultOperations">
            <el-button size="small" type="primary" @click="$emit('view', scope.row)">
              查看
            </el-button>
            <el-button size="small" type="primary" @click="$emit('edit', scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="$emit('delete', scope.row)">
              删除
            </el-button>
          </el-button-group>
        </slot>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { ref, computed, watch, shallowRef } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElButtonGroup } from 'element-plus'

// 类型定义
type ColumnType = 'default' | 'expand' | 'selection' | 'index'
type Align = 'left' | 'center' | 'right'
type Fixed = 'left' | 'right' | boolean

// 表格列配置
interface TableColumn {
  type?: ColumnType
  prop?: string
  label: string
  width?: string | number
  minWidth?: string | number
  align?: Align
  sortable?: boolean | string
  fixed?: Fixed
  slot?: string
  formatter?: (row: any, column: any, cellValue: any, index: number) => any
  'show-overflow-tooltip'?: boolean
}

// 表格配置
interface BaseTableProps {
  data: any[]
  loading?: boolean
  columns: TableColumn[]
  showSelection?: boolean
  showOperation?: boolean
  operationLabel?: string
  operationWidth?: string | number
  operationFixed?: Fixed
  showDefaultOperations?: boolean
  highlight?: boolean
  highlightKey?: string
  virtual?: boolean
  rowHeight?: number
  maxHeight?: number
}

const props = withDefaults(defineProps<BaseTableProps>(), {
  loading: false,
  showSelection: false,
  showOperation: true,
  operationLabel: '操作',
  operationWidth: 150,
  operationFixed: 'right',
  showDefaultOperations: true,
  highlight: false,
  highlightKey: '',
  virtual: false,
  rowHeight: 60,
  maxHeight: 600,
})

const emit = defineEmits<{
  (e: 'selection-change', selection: any[]): void
  (e: 'edit', row: any): void
  (e: 'delete', row: any): void
  (e: 'view', row: any): void
  (e: 'lock', row: any): void
  (e: 'unlock', row: any): void
  (e: 'distribute', row: any): void
  (e: 'createParty', row: any): void
  (e: 'sort-change', sort: { prop: string; order: string | null }): void
}>()

const tableRef = ref()

const hasOperationColumn = computed(() => {
  return props.columns.some(column => column.prop === 'operation' || column.slot === 'operation')
})

const tableData = shallowRef(props.data)

watch(
  () => props.data,
  (newData) => {
    tableData.value = newData
  },
  { deep: true }
)

const handleSelectionChange = (selection: any[]) => {
  emit('selection-change', selection)
}

const handleSortChange = (sort: { prop: string; order: string | null }) => {
  emit('sort-change', sort)
}

defineExpose({
  tableRef,
  clearSelection: () => tableRef.value?.clearSelection(),
  toggleRowSelection: (row: any, selected?: boolean) =>
    tableRef.value?.toggleRowSelection(row, selected),
  toggleAllSelection: () => tableRef.value?.toggleAllSelection(),
  toggleRowExpansion: (row: any, expanded?: boolean) =>
    tableRef.value?.toggleRowExpansion(row, expanded),
  setCurrentRow: (row: any) => tableRef.value?.setCurrentRow(row),
  clearSort: () => tableRef.value?.clearSort(),
  doLayout: () => tableRef.value?.doLayout(),
})
</script>

<style scoped>
  .el-table {
    /* 性能优化：启用GPU加速 */
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
  }

  /* 表格行悬停效果优化 */
  :deep(.el-table__row) {
    transition: background-color 0.2s ease;
  }

  /* 高亮行样式 */
  :deep(.el-table__row.is-highlight) {
    background-color: var(--el-color-primary-light-9) !important;
  }

  /* 优化表格渲染性能 */
  :deep(.el-table__body-wrapper) {
    /* 开启硬件加速 */
    will-change: scroll;
    -webkit-overflow-scrolling: touch;
  }

  /* 操作按钮组优化 */
  :deep(.el-button-group) {
    display: flex;
    gap: 4px;
  }

  /* 响应式优化 */
  @media (max-width: 768px) {
    .el-table {
      font-size: 12px;
    }
  }
</style>
